package com.wq.code;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: wangqiang20995
 * @Date:2019/5/15
 * @Description:
 * @Resource:
 */
public class NetInterfaceHelper {

    private static final String LOCAL_HOST = "127.0.0.1";
    private static final String ANYHOST = "0.0.0.0";
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

    public static List<InetAddress> allNetAddress(){
        try {
            List<InetAddress> all = new ArrayList<>();
            Enumeration<NetworkInterface> allNets = NetworkInterface.getNetworkInterfaces();
            while (allNets.hasMoreElements()){
                NetworkInterface singleNet = allNets.nextElement();
                Enumeration<InetAddress> address = singleNet.getInetAddresses();

                if(address != null){
                    while (address.hasMoreElements()){
                        InetAddress inetAddress = address.nextElement();
                        if(validAddress(inetAddress)) {
                            all.add(inetAddress);
                        }
                    }
                }
            }

            return all;
        } catch (SocketException e) {
            System.err.println(e.getMessage());
            return new ArrayList<>();
        }
    }

    private static boolean validAddress(InetAddress inetAddress){
        if(inetAddress == null || inetAddress.isLoopbackAddress()){
            return false;
        }

        String address = inetAddress.getHostAddress();
        return address != null && !address.equals(ANYHOST)
                && !address.equals(LOCAL_HOST) && IP_PATTERN.matcher(address).matches();

    }

    public static void main(String[] args){
        System.out.println(allNetAddress());
    }
}
